package afcp.alumni.security;
/**
 * 
 */


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.security.StripesSecurityManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.MyActionBeanContext;
import afcp.alumni.model.db.Member;
import afcp.alumni.model.db.Member.Role;

/**
 * @author Antoine
 * 
 */
public class MySecurityManager
	implements StripesSecurityManager
{
	
	private static final Log logger = LogFactory.getLog(MySecurityManager.class);
	
	@Override
	public boolean isUserInRole(List<String> roles, ActionBeanContext context)
	{
		return isUserInRole(roles, context.getRequest());
	}

	@Override
	public boolean isUserInRole(List<String> roles, HttpServletRequest request,
			HttpServletResponse response) {
		return isUserInRole(roles, request);
	}

	public boolean isUserInRole(List<String> roles, HttpServletRequest request) {
		try {
			List<Role> userRoles = getCurrentUserRoles(request);
			
			
			if (logger.isDebugEnabled()) {
				StringBuilder userRolesStringBuilder = new StringBuilder();
				if (userRoles != null) {
					for (Role userRole : userRoles) {
						if (userRole != null) {
							userRolesStringBuilder.append(userRole + ",");
						}
					}
				}
				String userRolesString = userRolesStringBuilder.toString();
				StringBuilder rolesBuilder = new StringBuilder();
				for (String role : roles) {
					rolesBuilder.append(role).append(",");
				}
				logger.debug("user role : " + userRolesString + " / tag role : " + rolesBuilder.toString());
			}
			

			// Authorized if:
			// - one of the user roles is included in the list of authorized roles
			// AND
			// - none of them are in the list of unauthorized roles
			for (String role : roles) {
				boolean allowAccessReturnValue = true;
				// Implementing the "not " operator in the role list
				if (role.length() > 4 && role.substring(0, 4).toLowerCase().equals("not ")) {
					allowAccessReturnValue = false;
					role = role.substring(4);
					if (userRoles == null) {
						return true;
					}
				}
				if (userRoles != null) {
					for (Role userRole : userRoles) {
						if (userRole != null && userRole.toString().equals(role)) {
							return allowAccessReturnValue;
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("Could not check the current user role because an"
					+ " unknown exception occurred.", e);
		}
		return false;
	}
	
	private List<Role> getCurrentUserRoles(HttpServletRequest request) {
//		return (List<String>) request.getSession().getAttribute("roles");
		Member member = (Member) request.getSession().getAttribute(MyActionBeanContext.SESSION_USER);
		return member == null ? null : member.getRoles();
	}

//	/**
//	 * Methode static privée
//	 * 
//	 * @params roles : liste des rôles autorisés pour l'affichage de l'élément
//	 * @params session : La Session de l'utilisateur
//	 * @return boolean : true si autorisation ok sinon false
//	 */
//	private boolean checkUserRole(List<String> roles, HttpServletRequest request) {
//		ActionContextAdapter ctx = new ActionContextAdapter();
//		ctx.setRequest(request);
//		boolean containsRole = false;
//		for(String role : roles)
//		{
//			List<String> sessionRoles = ctx.getCurrentRoles();
//			if (sessionRoles != null && sessionRoles.contains(role)){
//				containsRole = true;
//			}
//		}
//		return containsRole;
//	}
//
//	private void logout(HttpSession session) {
//		session.removeAttribute(ActionContextAdapter.USER);
//		session.removeAttribute(ActionContextAdapter.ADMIN);
//	}
//	
//	public void logoutServer(HttpSession session) {
//		if (session != null) {
//			logout(session);
//			session.invalidate();
//		}
//	}
}
